# -*- coding: utf-8 -*-

#    OriginDB
#    Copyright (C) 2010  Jason Power <power.jg@gmail.com>
#    Copyright (C) 2010  Travis Gockel <travis@gockelhut.com>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License along
#    with this program; if not, write to the Free Software Foundation, Inc.,
#    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

from PyQt4 import QtCore
from PyQt4.QtGui import *

from sys import path
path.append("../")

import aeDatabase as database

from ui_visualWindow import Ui_VisualWindow
from ui_description import Ui_DescriptionDialog

from pathwayScene import PathwayScene
from reactionVisual import ReactionVisual
from compoundVisual import CompoundVisual
from filterTabWidget import FilterFrame
from detailsFrame import DetailsWidget


# Take out later
from tools import *

class VisualWindow(QMainWindow):
	def __init__(self, parent, controller):
		QMainWindow.__init__(self, parent)
		
		self.controller = controller

		self.ui = Ui_VisualWindow()
		self.ui.setupUi(self)

		self.setupCentralWidget()
		self.setupMenus()
		
		self.progressBar = QProgressBar()
		self.statusBar().addWidget(self.progressBar)

		self.description = ""

		#r2 = database.Reaction("aghvcmlnaW5kYnIQCxIIUmVhY3Rpb24Yi7wBDA")
		#r = database.Reaction("aghvcmlnaW5kYnIPCxIIUmVhY3Rpb24Y_G0M")
		#r3 = database.Reaction("aghvcmlnaW5kYnIQCxIIUmVhY3Rpb24Yk-MBDA")

		#rVis2 = ReactionVisual(r2)
		#rVis = ReactionVisual(r)
		#rVis3 = ReactionVisual(r3)
		#rVis.setPos(250,50)
		#rVis2.setPos(0,100)

		#command1 = AddReactionVisual(rVis2, self.pathwayScene)
		#command2 = AddReactionVisual(rVis3, self.pathwayScene)
		#command3 = AddReactionVisual(rVis, self.pathwayScene)
		#self.pathwayScene.undoStack.push(command1)
		#self.pathwayScene.undoStack.push(command2)
		#self.pathwayScene.undoStack.push(command3)

		#self.filterFrame.resultsScene.addReactions([r])

		self.connect(self.ui.actionNewPathway, QtCore.SIGNAL("triggered()"), self.newPathway)
		self.connect(self.ui.actionLoadFromFile, QtCore.SIGNAL("triggered()"), self.loadFromFile)
		self.connect(self.ui.actionLoadFromDb, QtCore.SIGNAL("triggered()"), self.blank)
		self.connect(self.ui.actionSaveToFile, QtCore.SIGNAL("triggered()"), self.saveToFile)
		self.connect(self.ui.actionSaveToDb, QtCore.SIGNAL("triggered()"), self.saveToDb)

		self.connect(self.ui.nameLineEdit, QtCore.SIGNAL("editingFinished()"), self.changeTitle)
		self.connect(self.ui.descriptionButton, QtCore.SIGNAL("clicked()"), self.changeDescription)
		
		self.connect(self.actionMove, QtCore.SIGNAL("triggered()"), self.changeAction)
		self.connect(self.actionConnection, QtCore.SIGNAL("triggered()"), self.changeAction)
		self.connect(self.actionEraser, QtCore.SIGNAL("triggered()"), self.changeAction)
		
		self.connect(self.actionClean, QtCore.SIGNAL("triggered()"), self.cleanDisplay)
		
		self.connect(self.undoAction, QtCore.SIGNAL("triggered()"), self.pathwayScene.undoStack.undo)
		self.connect(self.redoAction, QtCore.SIGNAL("triggered()"), self.pathwayScene.undoStack.redo)

	def sizeHint(self):
		return QtCore.QSize(1024,800)

	def blank(self):
		pass

	def cleanDisplay(self):
		self.pathwayScene.clean()

	def changeAction(self):
		if self.actionMove.isChecked():
			self.pathwayScene.setTool("move")
		if self.actionConnection.isChecked():
			self.pathwayScene.setTool("draw")
		if self.actionEraser.isChecked():
			self.pathwayScene.setTool("erase")

	def newPathway(self):
		self.pathwayScene.clear()
		self.ui.nameLineEdit.clear()
		self.description = ""

	def saveToFile(self):
		filename = str(QFileDialog.getSaveFileName(self))
		if (filename):
			with open(filename, 'w') as f:
				pathway = self.pathwayScene.getPathway()
				pathway.name = str(self.ui.nameLineEdit.text())
				pathway.description = self.description
				f.write(pathway._dumpYAML())

	def loadFromFile(self):
		filename = str(QFileDialog.getOpenFileName(self))
		if (filename):
			with open(filename, 'r') as f:
				pathway = database.Pathway()
				pathway._loadYAML(f.read())
				print pathway
				
				self.ui.nameLineEdit.setText(pathway.name)
				self.description = pathway.description
				self.changeTitle()
				
				self.pathwayScene.setPathway(pathway)

	def saveToDb(self):
		name = str(self.ui.nameLineEdit.text())
		if not name:
			msgDialog = QMessageBox(QMessageBox.Critical, "No Name", "Please provide a unique name for your pathway", QMessageBox.Ok)
			msgDialog.exec_()
			return
		pathway = self.pathwayScene.getPathway()
		pathway.name = name
		pathway.description = self.description
		pathway.insert()

	def changeTitle(self):
		if str(self.ui.nameLineEdit.text()):
			self.setWindowTitle("Pathway Editor - " + str(self.ui.nameLineEdit.text()))
		else:
			self.setWindowTitle("Pathway Editor")

	def changeDescription(self):
		dialog = QDialog()
		dialog.ui = Ui_DescriptionDialog()
		dialog.ui.setupUi(dialog)
		dialog.ui.textEdit.setPlainText(self.description)
		if dialog.exec_() == 1:
			self.description = str(dialog.ui.textEdit.toPlainText())
		

	def setupCentralWidget(self):
		self.detailsFrame = DetailsWidget()

		self.pathwayScene = PathwayScene()
		self.ui.pathwayView.setScene(self.pathwayScene)
		self.pathwayScene.reactionDetails = self.detailsFrame

		self.filterFrame = FilterFrame(self.detailsFrame, self.pathwayScene)

		self.horizSplitter = QSplitter(QtCore.Qt.Horizontal)
		self.vertSplitter = QSplitter(QtCore.Qt.Vertical)

		self.horizSplitter.addWidget(self.detailsFrame)
		self.horizSplitter.addWidget(self.filterFrame)

		self.vertSplitter.addWidget(self.ui.pathwayFrame)
		self.vertSplitter.addWidget(self.horizSplitter)

		self.setCentralWidget(self.vertSplitter)

		self.vertSplitter.setSizes([400, 400])
		self.horizSplitter.setSizes([300,500])

	def setupMenus(self):
		self.toolGroup = QActionGroup(self)
		self.toolGroup.setExclusive(True)

		self.actionConnection = QAction("Connection Tool", self)
		self.actionConnection.setCheckable(True)
		icon = QIcon()
		icon.addPixmap(QPixmap(":/images/draw-freehand.png"), QIcon.Normal, QIcon.Off)
		self.actionConnection.setIcon(icon)
		self.actionConnection.setActionGroup(self.toolGroup)

		self.actionEraser = QAction("Eraser Tool", self)
		self.actionEraser.setCheckable(True)
		icon1 = QIcon()
		icon1.addPixmap(QPixmap(":/images/draw-eraser.png"), QIcon.Normal, QIcon.Off)
		self.actionEraser.setIcon(icon1)
		self.actionEraser.setActionGroup(self.toolGroup)

		self.actionMove = QAction("Move Tool", self)
		self.actionMove.setCheckable(True)
		icon2 = QIcon()
		icon2.addPixmap(QPixmap(":/images/transform-move.png"), QIcon.Normal, QIcon.Off)
		self.actionMove.setIcon(icon2)
		self.actionMove.setActionGroup(self.toolGroup)

		self.actionClean = QAction("Clean Display", self)

		self.ui.menuTools.addAction(self.actionConnection)
		self.ui.menuTools.addAction(self.actionMove)
		self.ui.menuTools.addAction(self.actionEraser)

		self.ui.toolBar.addAction(self.actionConnection)
		self.ui.toolBar.addAction(self.actionMove)
		self.ui.toolBar.addAction(self.actionEraser)

		self.actionMove.setChecked(True)
		
		self.ui.toolBar.addAction(self.actionClean)

		self.undoAction = QAction("Undo", self)
		self.undoAction.setShortcut(QKeySequence.Undo)
		self.redoAction = QAction("Redo", self)
		self.redoAction.setShortcut(QKeySequence.Redo)

		self.ui.editMenu.addAction(self.undoAction)
		self.ui.editMenu.addAction(self.redoAction)
